<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="100px"
    v-loading="formLoading"
  >
    <el-row :span="24">
      <el-col :span="12">
        <el-form-item label="申请编号" prop="applyCode">
          <el-input v-model="formData.applyCode" placeholder="请输入申请编号" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="申请人" prop="applyUserId">
          <UserSelect
            v-model="formData.applyUserId"
            placeholder="请选择申请人"
            clearable
            filterable
            @change="onChangeUser"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="formData.phone" placeholder="自动带出" clearable disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="使用期限" prop="useEndTime">
          <el-date-picker
            v-model="formData.useEndTime"
            value-format="x"
            type="datetime"
            placeholder="使用期限"
            :default-time="new Date('1 23:59:59')"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="使用理由" prop="applyReson">
          <el-input v-model="formData.applyReson" type="textarea" placeholder="请输入使用理由" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="附件" prop="file">
          <UploadFile 
            v-model="formData.file" 
            :limit="1"
            :fileType="fileExtsApplyList"
            :fileSize="200"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-divider content-position="left">数字资源</el-divider>
    <el-form-item prop="sourceApplyDetails" label-width="0">
      <div class="flex items-center justify-end" style="width: 100%;">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="formData.sourceApplyDetails" :stripe="true" :show-overflow-tooltip="true">
        <!-- <el-table-column label="主键" align="center" prop="id" /> -->
        <el-table-column label="资源编号" align="center" prop="sourceCode" />
        <el-table-column label="封面" align="center" prop="mainImage">
          <template #default="scope">
            <el-image
              style="width: 44px; height: 44px;"
              :src="scope.row.mainImage"
              :preview-src-list="[scope.row.mainImage]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="资源名称" align="center" prop="sourceName" />
        <el-table-column label="资源类型" align="center" prop="sourceType">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SOURCE_TYPE" :value="scope.row.sourceType" />
          </template>
        </el-table-column>
        <el-table-column label="来源信息" align="center" prop="sourceDesc">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SOURCE_DESC" :value="scope.row.sourceDesc" />
          </template>
        </el-table-column>
        <el-table-column label="资源来源" align="center" prop="sourceFrom">
          <template #default="scope">
            <!-- <dict-tag :type="DICT_TYPE.SOURCE_FROM" :value="scope.row.sourceFrom" /> -->
            {{ scope.row.sourceFrom }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120px" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openDetail(scope.row)"
              v-hasPermi="['dr:source:query']"
            >
              详情
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-form>
  <div style="text-align: center;">
    <el-button @click="cancleForm">取 消</el-button>
    <el-button @click="submitForm('save')" type="primary" :disabled="formLoading">暂 存</el-button>
    <el-button @click="submitForm('submit')" type="primary" :disabled="formLoading">确 定</el-button>
  </div>

  <!-- 资源详情 -->
  <SourceDetail v-model:visible="detailVisible" :data="currentRow" />
  <!-- 资源搜索 -->
  <SourceSelectDialog
    v-model:visible="detailSourceSelectVisible"
    v-model="formData.sourceApplyDetails"
    type="apply"
  />
</template>
<script setup lang="ts">
import { useTagsViewStore } from '@/store/modules/tagsView'
import { getStrDictOptions, fileExtsApplyList, DICT_TYPE } from '@/utils/dict'
import { SourceApplyApi, SourceApplyVO } from '@/api/dr/sourceapply'
import { getSimpleUserList } from '@/api/system/user'
import { SourceVO } from '@/api/dr/source'

/** 资源申请 表单 */
defineOptions({ name: 'SourceApplyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const applyUserList = ref<any>([]) // 申请人列表
const formData = ref<any>({
  id: undefined,
  applyCode: undefined,
  applyUserId: undefined,
  phone: undefined,
  useEndTime: undefined,
  applyReson: undefined,
  file: undefined,
  sourceApplyDetails: []
})
const formRules = reactive({
  applyUserId: [
    {
      required: true,
      message: '请输入申请人',
      trigger: ['blur', 'change'],
    },
  ],
  useEndTime: [
    {
      required: true,
      message: '请选择使用期限',
      trigger: ['blur', 'change'],
    },
  ],
})
const formRef = ref() // 表单 Ref
const detailVisible = ref<boolean>(false)
const currentRow = ref<SourceVO>()
const detailSourceSelectVisible = ref<boolean>(false)
// 新增资源
const handleAdd = () => {
  detailSourceSelectVisible.value = true
}
const handleDelete = (id: number) => {
  formData.value.sourceApplyDetails = formData.value.sourceApplyDetails.filter((item: SourceVO) => item.id !== id)
}
// 详情弹窗
const openDetail = (row: any) => {
  currentRow.value = { ...row }
  detailVisible.value = true
}
const onChangeUser = (value: any, e:any) => {
  // console.log('onChangeUser', value, e)
  formData.value.phone = e.mobile
}

/** 打开弹窗 */
const open = async () => {
  const id:any = currentRoute.value.query.id
  formType.value = id ? 'edit' : 'create'
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SourceApplyApi.getSourceApply(id)
      formData.value.sourceApplyDetails = formData.value.sourceList?.slice() || []
      delete formData.value.sourceList
    } finally {
      formLoading.value = false
    }
  }

  getSimpleUserList().then(list => {
    // console.log('getSimpleUserList', list)
    applyUserList.value = list
  })
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type?:string) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SourceApplyVO
    data.operateFlag = type
    data.sourceApplyDetails = data.sourceApplyDetails?.map((v:any) => ({
      ...v,
      sourceId: v.id
    }))
    if (formType.value === 'create') {
      await SourceApplyApi.createSourceApplyBpm(data)
      message.success(t('common.createSuccess'))
    } else {
      await SourceApplyApi.updateSourceApply(data)
      message.success(t('common.updateSuccess'))
    }
    // 关闭当前 Tab
    cancleForm()
  } finally {
    formLoading.value = false
  }
}

const cancleForm = async() => {
  delView(unref(currentRoute))
  await push({ name: 'SourceApply' })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    applyCode: undefined,
    applyUserId: undefined,
    phone: undefined,
    useEndTime: undefined,
    applyReson: undefined,
    file: undefined,
    sourceApplyDetails: []
  }
  formRef.value?.resetFields()
}

onMounted(() => {
  open()
})
</script>
